package com.share.controller;

import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.share.domain.Const;
import com.share.domain.Result;
import com.share.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Principal;
import java.util.UUID;

/**
 * @program: share-admin
 * 描述：
 * @author: XLX
 * @create: 2022-11-30 22:11
 **/
@RestController
public class AuthController extends BaseController {

    @Autowired
    Producer producer;

    @Value(value = "${uploadPath}")
    String uploadPath;


    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        System.out.print("验证码:");
        String key = UUID.randomUUID().toString();
        String code = producer.createText();
        System.out.println(code);

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpg;base64,";
        String base64Img = str+encoder.encode(outputStream.toByteArray());

        redisUtil.hset(Const.CAPTCHA_KEY,key,code,120);
        return Result.succ(
                MapUtil.builder().put("key",key).put("captchaImg",base64Img)
                .build()
        );
    }


    @GetMapping("/sys/userInfo")
    public Result userInfo(Principal principal){
        SysUser sysUser = sysUserService.getByUsername(principal.getName());

        return Result.succ(MapUtil.builder()
                .put("id",sysUser.getId())
                .put("username",sysUser.getUsername())
                .put("avatar",sysUser.getAvatar())
                .put("created",sysUser.getCreated())
                .map()
        );
    }


    @PostMapping(value = "/upload")
    @CrossOrigin(origins = "*")
    public Result fileUpload(
            MultipartFile file, HttpServletRequest req) throws FileNotFoundException {
        //获取数据
        //上传文件 ===>  返回一个文件名
        //项目真实路径   拼接上  upload包
        String realPath = ResourceUtils.getURL("classpath:static/img").getPath();
        System.out.println(realPath);

        File f = new File(realPath);
        if (!f.exists())f.mkdirs();
        //获取上传的文件名
        String oldName = file.getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String name = UUID.randomUUID().toString();
        String newName = name + suffix;
        //上传
        try {
            file.transferTo(new File(realPath+File.separator+newName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //数据库存储文件名称
        return Result.succ(200,"上传成功",uploadPath+File.separator+newName);

    }

}